import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { Link } from 'react-router-dom';
import {
  PlusIcon,
  MagnifyingGlassIcon,
  FunnelIcon,
  FolderIcon,
  UserGroupIcon,
  CalendarIcon,
  PencilIcon,
  TrashIcon,
  ChartBarIcon,
} from '@heroicons/react/24/outline';
import api from '../services/api';
import LoadingSpinner from '../components/LoadingSpinner';
import toast from 'react-hot-toast';

const Projects = () => {
  const [filters, setFilters] = useState({
    search: '',
    status: '',
  });
  const [showFilters, setShowFilters] = useState(false);
  const queryClient = useQueryClient();

  // 获取项目列表
  const { data: projectsData, isLoading } = useQuery(
    ['projects', filters],
    () => api.get('/projects', { params: filters }),
    {
      keepPreviousData: true,
    }
  );

  // 删除项目
  const deleteProjectMutation = useMutation(
    (projectId) => api.delete(`/projects/${projectId}`),
    {
      onSuccess: () => {
        queryClient.invalidateQueries('projects');
        toast.success('项目删除成功');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '删除失败');
      },
    }
  );

  const handleFilterChange = (key, value) => {
    setFilters(prev => ({
      ...prev,
      [key]: value,
    }));
  };

  const handleDeleteProject = (projectId, projectName) => {
    if (window.confirm(`确定要删除项目 "${projectName}" 吗？这将删除项目下的所有任务。`)) {
      deleteProjectMutation.mutate(projectId);
    }
  };

  const getProgressColor = (progress) => {
    if (progress >= 80) return 'bg-success-500';
    if (progress >= 60) return 'bg-warning-500';
    if (progress >= 40) return 'bg-primary-500';
    return 'bg-gray-300';
  };

  const formatDate = (dateString) => {
    if (!dateString) return '无截止日期';
    return new Date(dateString).toLocaleDateString();
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  const projects = projectsData?.data?.projects || [];

  return (
    <div className="space-y-6">
      {/* 页面标题和操作 */}
      <div className="sm:flex sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">项目管理</h1>
          <p className="mt-1 text-sm text-gray-500">
            组织和管理您的项目，跟踪项目进度
          </p>
        </div>
        <div className="mt-4 sm:mt-0">
          <Link
            to="/projects/new"
            className="btn-primary"
          >
            <PlusIcon className="h-4 w-4 mr-2" />
            创建项目
          </Link>
        </div>
      </div>

      {/* 搜索和筛选 */}
      <div className="card">
        <div className="card-body">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-4 sm:space-y-0">
            <div className="flex-1 max-w-lg">
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />
                </div>
                <input
                  type="text"
                  placeholder="搜索项目..."
                  className="input pl-10"
                  value={filters.search}
                  onChange={(e) => handleFilterChange('search', e.target.value)}
                />
              </div>
            </div>
            <div className="flex items-center space-x-4">
              <button
                onClick={() => setShowFilters(!showFilters)}
                className="btn-outline"
              >
                <FunnelIcon className="h-4 w-4 mr-2" />
                筛选
              </button>
            </div>
          </div>

          {/* 筛选选项 */}
          {showFilters && (
            <div className="mt-4 pt-4 border-t border-gray-200">
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div>
                  <label className="block text-sm font-medium text-gray-700">状态</label>
                  <select
                    className="mt-1 input"
                    value={filters.status}
                    onChange={(e) => handleFilterChange('status', e.target.value)}
                  >
                    <option value="">全部状态</option>
                    <option value="active">活跃</option>
                    <option value="archived">已归档</option>
                  </select>
                </div>
                <div className="flex items-end">
                  <button
                    onClick={() => setFilters({ search: '', status: '' })}
                    className="btn-outline w-full"
                  >
                    清除筛选
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 项目列表 */}
      {projects.length > 0 ? (
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {projects.map((project) => (
            <div key={project.id} className="card hover:shadow-md transition-shadow duration-200">
              <div className="card-body">
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-3">
                      <FolderIcon className="h-8 w-8 text-primary-600 flex-shrink-0" />
                      <div className="flex-1 min-w-0">
                        <h3 className="text-lg font-medium text-gray-900 truncate">
                          {project.name}
                        </h3>
                        <p className="text-sm text-gray-500 truncate">
                          {project.description || '无描述'}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                {/* 项目统计 */}
                <div className="mt-4 space-y-3">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-500">进度</span>
                    <span className="font-medium text-gray-900">
                      {project.completed_tasks || 0} / {project.task_count || 0} 任务
                    </span>
                  </div>
                  
                  {/* 进度条 */}
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className={`h-2 rounded-full ${getProgressColor(
                        project.task_count > 0 
                          ? ((project.completed_tasks || 0) / project.task_count) * 100 
                          : 0
                      )}`}
                      style={{
                        width: `${project.task_count > 0 
                          ? ((project.completed_tasks || 0) / project.task_count) * 100 
                          : 0}%`
                      }}
                    />
                  </div>

                  <div className="flex items-center justify-between text-sm text-gray-500">
                    <div className="flex items-center space-x-4">
                      {project.team && (
                        <div className="flex items-center">
                          <UserGroupIcon className="h-4 w-4 mr-1" />
                          <span>{project.team.name}</span>
                        </div>
                      )}
                      {project.end_date && (
                        <div className="flex items-center">
                          <CalendarIcon className="h-4 w-4 mr-1" />
                          <span>{formatDate(project.end_date)}</span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* 操作按钮 */}
                <div className="mt-4 flex items-center justify-between">
                  <div className="flex space-x-2">
                    <Link
                      to={`/projects/${project.id}`}
                      className="btn-outline text-sm"
                    >
                      查看详情
                    </Link>
                    <Link
                      to={`/projects/${project.id}/tasks`}
                      className="btn-outline text-sm"
                    >
                      管理任务
                    </Link>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Link
                      to={`/projects/${project.id}/edit`}
                      className="text-primary-600 hover:text-primary-700"
                      title="编辑项目"
                    >
                      <PencilIcon className="h-4 w-4" />
                    </Link>
                    <button
                      onClick={() => handleDeleteProject(project.id, project.name)}
                      className="text-danger-600 hover:text-danger-700"
                      title="删除项目"
                    >
                      <TrashIcon className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="card">
          <div className="card-body text-center py-12">
            <FolderIcon className="mx-auto h-12 w-12 text-gray-400" />
            <h3 className="mt-2 text-sm font-medium text-gray-900">暂无项目</h3>
            <p className="mt-1 text-sm text-gray-500">开始创建您的第一个项目吧！</p>
            <div className="mt-6">
              <Link to="/projects/new" className="btn-primary">
                创建项目
              </Link>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Projects;
